<?php

namespace Library\Rabbitmq;

use \PhpAmqpLib\Exception\AMQPTimeoutException;

/**
 * rabbitmq Routing模式
 */
class Routing extends Msg
{
    protected $consumerAck = false;
    protected $exchange = 'routing_exchange'; 
    protected $queue = ''; 
    protected $queueArray = ['routing_queue_1'=>['info','error'],'routing_queue_2'=>['info']]; 

    public function __construct($exchange = '',$queueConsumer='',$isConsumer=false,$consumerAck = false)
    {
        if($exchange){
            $this->exchange = $exchange;
        }
        $this->consumerAck = $consumerAck;
        //parent::__construct();
        $this->connect();
        if(!$isConsumer){
            $this->queue_set_publish();
        }else{
            $this->queue = $queueConsumer;
            $this->queue_set_consumer();
        }
    }

    //创建queue
    private function routing_queue($queue,$routeKey)
    {
        $this->channel->queue_declare($queue, false, false, false, false);
        $this->channel->exchange_declare($this->exchange, 'direct', false, false, false);
        $this->channel->queue_bind($queue, $this->exchange,$routeKey);
    }

    public function routing_queue_create()
    {
        foreach($this->queueArray as $key=>$val){
            foreach($val as $k=>$v){
                $this->routing_queue($key,$v);
            }
        }
    }
    
    
    //生产着 //路由声明
    public function queue_set_publish()
    {
        $this->channel->exchange_declare($this->exchange, 'direct', false, false, false);
    }

    //消费者
    public function queue_set_consumer()
    {
        $this->channel->exchange_declare($this->exchange, 'direct', false, false, false);
        //创建随机名称队列
        // list($queue_name, ,) = $this->channel->queue_declare("", false, false, false, false);
        // $this->queue = $queue_name;
        // foreach($routeKey as $key=>$val){
        //     $this->channel->queue_bind($queue_name, $this->exchange,$val);
        // }
    }

    /**
     * 生产者 
     * 参数只有$content
     */
    public function publish($content, $exchange='', $routeKey='', $head = [])
    {
        return parent::publish($content, $this->exchange, $routeKey, $head = []);
    }

    /**
     * 消费者
     */
    public function consumer($call_back,$consumerTag='')
    {
        try{
            $this->channel->basic_qos( null , 3 , null );
            if($this->consumerAck){
                $this->channel->basic_consume($this->queue, $consumerTag='', false, false, false, false, $call_back);
            }else{
                $this->channel->basic_consume($this->queue, $consumerTag='', false, true, false, false, $call_back); //不需要确认回复
            }
            //$channel->isOpen 暂时不知道区别
            while (count($this->channel->callbacks)) {
                $this->channel->wait();
            }
        }catch(AMQPTimeoutException $e){
            throw $e;
        }
        
    }

}